package com.cetc.stream;

import com.cetc.lambda.Person;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;

/**
 * @Classname StreamTest06
 * @Description 归约 reduce的使用
 * @Date 2023/1/17 16:37
 * @Created by louzhuangxi
 */
public class StreamTest06 {
    @Test
    public void test01() {
        System.out.println("**********************************求和*****************************");
        List<Integer> numbers = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            numbers.add(i);
        }

        Integer result = numbers.stream().reduce(0, Integer::sum);
        System.out.println(result);

        Integer result2 = numbers.parallelStream().reduce(0, Integer::sum);
        System.out.println(result2);

        List<Person> personList = Arrays.asList(
                new Person("张三", 24),
                new Person("李四", 80),
                new Person("王五", 28),
                new Person("赵六2", 42),
                new Person("赵六1", 42),
                new Person("田七", 28)
        );
        Integer sum = personList.stream().reduce(0, (t1, t2) -> t1 + t2.getAge(), Integer::sum);
        System.out.println("年龄总和为:" + sum);

        System.out.println("**********************************异常处理*****************************");
        List<Integer> iList = Arrays.asList(1, 2, 3, 4, 5, 6);
        Integer divide = divide(iList);
        System.out.println(divide);
    }

    public static Integer divide(List<Integer> iList) {
        int divide = 1;
        return iList.stream().reduce(0, (a, b) -> {
            try {
                return a / divide + b / divide;
            } catch (RuntimeException e) {
                System.out.println("错误:" + e.getMessage());
            }
            return 0;
        });
    }
}
